package tree.binary;

import entity.tree.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

public class leetcode623在二叉树中增加一行 {
    public TreeNode addOneRow(TreeNode root, int val, int depth) {
        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode pre = new TreeNode(-1);
        pre.left = root;
        int level = 1;
        queue.offer(pre);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (level == depth) {
                    TreeNode left = new TreeNode(val);
                    TreeNode right = new TreeNode(val);
                    left.left = node.left;
                    right.right = node.right;
                    node.left = left;
                    node.right = right;
                }
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            if (level == depth) {
                break;
            }
            level++;
        }
        return pre.left;
    }
}
